<?php
/**
 * The Categories model class for abstracting operations to the Categories Entity
 *
 */

class Categories extends Zend_Db_Table
{
    protected $_name = 'categories';
    protected $_primary = 'cid';

    public function getCategories($cid = 0)
    {
        if($cid != 0)
        {
            $select = $this->select()->where('pid = ?', $cid)->where('cid <> pid');
        }
        else
        {
            $select = $this->select()->where('level = ?', 1);
        }
        $select->from('categories', array('cid', 'pid', 'name', 'level'))->order('name ASC');
        $rows = $this->fetchAll($select)->toArray();
        return $rows;
    }

    public function getCategoryParents($pid)
    {

        $select = $this->select()->where('cid = ?', $pid);

        $select->from('categories', array('cid', 'pid', 'name', 'level'))->order('name ASC');
        $row = $this->fetchRow($select);

        if($row->cid == $row->pid)
        {
            return $this->getCategories();
        } else
        {
            return $this->getCategories($row->pid);
        }
    }
}
